import {
	qiniuUpload
} from '../api/user.js'
import * as qiniu from 'qiniu-js'

export const getQiniuToken = async () => {
	// 需对接后端接口获取临时上传凭证（避免暴露AK/SK）
	const res = await qiniuUpload();
	console.log('获取成功七牛云token');
	console.log(res);
	return res.data.token
}

export const uploadToQiniu = async (filePath) => {
	const token = await getQiniuToken()
	const key = `uploads/${Date.now()}_${Math.random().toString(16).slice(2)}`

	// H5端使用SDK
	if (uni.getSystemInfoSync().platform === 'h5') {
		const observable = qiniu.upload(
			filePath,
			key,
			token
		)
		return new Promise((resolve, reject) => {
			observable.subscribe({
				error: reject,
				complete: (res) => resolve(`${this.domain}/${res.key}`)
			})
		})
	} else {
		const {
			data
		} = await uni.uploadFile({
			url: 'https://upload-z2.qiniup.com',
			filePath,
			name: 'file',
			formData: {
				token,
				key
			}
		})
		return JSON.parse(data).url
	}
}